package com.mrx.xfriendship.controller;

import com.mrx.commons.config.Constant;
import com.mrx.commons.exception.BusinessException;
import com.mrx.xfriendship.model.dto.ErrorInfoDTO;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * 全局异常处理控制器
 *
 * @ignore
 */
@Controller
public class XErrorController implements ErrorController {

    /**
     * 拦截所有的异常并将其抛出<br/>
     * 可以在 过滤器 里使用 {@link HttpServletRequest#getRequestDispatcher(String)} 来转发异常到本接口<br/>
     * 一个典型的用法是:<br/>
     * <pre>
     *  request.setAttribute(Constant.ERROR_ATTRIBUTE, e);
     *  request.getRequestDispatcher("/error").forward(request, response);
     * </pre>
     *
     * @param request 本次 request
     * @throws Throwable 抛出所有异常
     */
    @RequestMapping("/error")
    public void handleError(HttpServletRequest request) throws Throwable {
        throw (Throwable) Optional
                .ofNullable(request.getAttribute(Constant.ERROR_ATTRIBUTE))
                .orElseGet(() -> new BusinessException(ErrorInfoDTO.of(request)));
    }

}